import { getLoggedInUser, logoutUAA, logout, getUserAccessesMap } from '@/api/security'
import storage from '@/utils/storage'
import router, { constantRouterMap, generateRouters } from '@/router'
import { toTreeData } from '@/utils/util'
import i18n from '@/lang'
import axios from 'axios'

const user = {
  state: {
    loggedInUser: '',
    language: storage.getStorage('language') || 'en',
    languageData: {},
    menus: []
  },

  mutations: {
    SET_LOGIN_USER (state, loggedInUser) {
      state.loggedInUser = loggedInUser
    },
    SET_LANGUAGE: (state, language) => {
      state.language = language
      storage.setStorage('language', language)
      let eiLocale = i18n.getLocaleMessage(language)
      let newLocale = {...state.languageData[language], ...eiLocale}
      i18n.setLocaleMessage(language, newLocale)
      i18n.locale = language
    },
    SET_LANGUAGE_DATA: (state, data) => {
      state.languageData = data
    },
    SET_MENUS: (state, menus) => {
      storage.setSession('pl_menus', menus)
      state.menus = menus
    },
    SET_USER_ACCESSES (state, accesses) {
      storage.setSession('pl_accesses', accesses)
    }
  },

  actions: {
    setLanguage ({ commit }, language) {
      commit('SET_LANGUAGE', language)
    },
    loadLanguageData ({commit}) {
      // 加载国际化文件
      axios.get('static/config/language.json').then(response => {
        let data = {}
        if (typeof response.data === 'string') {
          data = eval('(' + response.data + ')')
        } else if (typeof response.data === 'object') {
          data = response.data
        }
        commit('SET_LANGUAGE_DATA', data)
      })
    },
    // 获取用户信息
    getLoggedInUser ({ commit }) {
      return new Promise((resolve, reject) => {
        let response = {
          'code': 'SECURITY-0000',
          'msg': '',
          'data': {
            'id': 'admin',
            'username': 'admin',
            'realname': '管理员',
            'password': '',
            'email': 'bin.gan@zetatech.com.cn',
            'telephone': '',
            'mobilePhone': '17356509291',
            'department': 'AAA',
            'section': '',
            'position': '',
            'enabled': true,
            'locale': 'zh',
            'createdBy': null,
            'createdTimestamp': null,
            'updatedBy': 'admin',
            'updatedTimestamp': '2020-10-10 12:44:53',
            'tenantIds': [
              'ZetaTech'
            ],
            'tenants': null,
            'isForceModifyPassword': false,
            'isNotificationModifyPassword': false,
            'passwordValidDays': 0,
            'passwordPatternErrorMsg': '大写字母，小写字母，数字和特殊字符，其中任意三种组合，且长度在8到15之间',
            'lastModifiedPasswordTimestamp': null,
            'lastLogonTimestamp': '2020-10-10 12:44:53',
            'initPassword': true
          },
          'success': true
        }
        if (response.success && (response.data !== null && response.data !== '')) {
          commit('SET_LOGIN_USER', response.data)
          resolve(response)
        } else {
          reject(response)
        }
      })
    },
    // 登出
    LogOut ({ commit }) {
      return new Promise((resolve, reject) => {
        logoutUAA().then(res => {
          logout().then(response => {
            commit('SET_LOGIN_USER', '')
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        }).catch(error => {
          reject(error)
        })
      })
    },
    GenerateMenus ({ commit }, obj) {
      return new Promise(resolve => {
        let treeData = []
        if (this.state.app.showDashboard) {
          let dashboard = { 'id': 0, 'accessCode': 'dashboard', 'accessName': 'menu.dashboard', 'accessIco': 'dashboard', 'parentAccessCode': 'dashboard' }
          treeData.unshift(dashboard)
        }
        treeData.push({ 'id': 1, 'accessCode': 'yearcompare', 'accessName': 'menu.chart', 'accessIco': 'yearcompare', 'parentAccessCode': 'chart' })
        treeData.push({ 'id': 2, 'accessCode': 'totalyearcountcompare', 'accessName': 'menu.chart', 'accessIco': 'totalyearcountcompare', 'parentAccessCode': 'chart' })
        let routers = generateRouters(treeData)
        constantRouterMap[0]['children'] = [...constantRouterMap[0].children, ...routers]
        constantRouterMap[0]['redirect'] = routers[0]['path']
        console.log(constantRouterMap)
        router.addRoutes(constantRouterMap)
        commit('SET_MENUS', treeData)
        resolve()
      })
    },
    // 生成权限
    GenerateAccess ({ commit }, obj) {
      return new Promise((resolve, reject) => {
        getUserAccessesMap(obj.tenantId, obj.appId, obj.userId).then(re => {
          if (re.success) {
            let accessesItem = []
            for (let item of re.data) {
              if (item.accessType === 'FUNCTION' && (item.userOriented || item.groupOriented)) {
                accessesItem.push((item.accessCode).replace(/[.]/g, '_'))
              }
            }
            commit('SET_USER_ACCESSES', accessesItem)
            resolve()
          } else {
            return false
          }
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
